package cn.edu.jju.psytest.web.validator;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import cn.edu.jju.psytest.model.entity.User;
import cn.edu.jju.psytest.model.vo.UserVo;
import cn.edu.jju.psytest.service.UserService;

@SuppressWarnings("restriction")
@Component
public class UserValidator implements Validator {

	private UserService userService;

	public boolean supports(Class<?> clazz) {
		return UserVo.class.equals(clazz);
	}

	public void validate(Object obj, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username",
				"error.username", "请填写！");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
				"error.password", "请填写！");

		UserVo userVo = (UserVo) obj;
		String username = userVo.getUsername();
		String password = userVo.getPassword();

		if (username.equals("") || password.equals("")) {
			return;
		}
		User user = userService.getUser(username);

		if (user == null) {
			errors.rejectValue("username", "error.login", "错误！");
		} else {
			if(!user.getPassword().equals(password)) {
				errors.rejectValue("password", "error.login", "错误！");
			}
		}
	}

	/**
	 * Getters And Setters
	 */
	public UserService getUserService() {
		return userService;
	}

	@Resource
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
